package com.sgb.kjwl.view.ui.fragment.enterprise;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentServiceclassBinding;
import com.sgb.knowledgeshare.utils.SharePermissionUtils;
import com.sgb.knowledgeshare.view.activity.HomeShareActivity;
import com.swgk.core.view.entity.ChannelEntity;
import com.sgb.kjwl.model.entity.ParentAreaEntity;
import com.sgb.kjwl.model.entity.enterprise.SecerTitleEntity;
import com.sgb.kjwl.view.event.CategoryEvent2;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.enterprise.ProfessionalQuoteActivity;
import com.sgb.kjwl.view.ui.adapter.enterprise.ServiceCategoryLeftAdpater;
import com.sgb.kjwl.view.ui.adapter.enterprise.ServiceCategoryRightAdapter;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.viewmodel.enterprise.ServiceClassViewModel;
import com.swgk.core.dialog.DialogHelperNew;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

public class ServiceClassFragment extends AppLazyFragment {

    private FragmentServiceclassBinding binding;
    private ServiceCategoryLeftAdpater leftAdapter;
    private ServiceClassViewModel mViewModel;
    private int leftPos = 0;
    private List<ChannelEntity> channelEntityList;

    public static ServiceClassFragment newInstance() {
        ServiceClassFragment fragment = new ServiceClassFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_serviceclass, container, false);
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        mViewModel = new ViewModelProvider(this).get(ServiceClassViewModel.class);
        binding.setVariable(BR.viewModel,mViewModel);
        binding.setLifecycleOwner(this);
        binding.actionBarTitle.setText("服务分类");
        binding.tabBar.setVisibility(View.VISIBLE);

        leftAdapter = new ServiceCategoryLeftAdpater(getActivity(), null);
        binding.leftRecycler.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        binding.leftRecycler.setAdapter(leftAdapter);
        leftAdapter.setItemSelect(true);

        leftAdapter.setOnItemClick(new AdapterOnItemClick<ParentAreaEntity<List<ParentAreaEntity<List<ParentAreaEntity>>>>>() {
            @Override
            public void onItemClick(ParentAreaEntity<List<ParentAreaEntity<List<ParentAreaEntity>>>> listParentAreaEntity, int position) {
                leftPos = position;
                if(listParentAreaEntity.getChildren().size()>0) {
                    binding.reNullLayout.setVisibility(View.GONE);
                    setRightAdapter(leftPos, listParentAreaEntity.getChildren());
                    binding.rightRecycler.scrollToPosition(0);
                    binding.rightRecycler.setVisibility(View.VISIBLE);
                }else{
                    binding.rightRecycler.setVisibility(View.GONE);
                    binding.reNullLayout.setVisibility(View.VISIBLE);

                }
            }
        });
        binding.rightRecycler.setPullRefreshEnabled(false);
        binding.rightRecycler.setLoadingMoreEnabled(false);
        binding.noDataCount.setOnClickListener(View ->{
            List<ParentAreaEntity<List<ParentAreaEntity<List<ParentAreaEntity>>>>> cacheList  = leftAdapter.getDatas();
            SecerTitleEntity entity = new SecerTitleEntity();
            entity.setCategoryFirstName(cacheList.get(leftPos).getName());
            entity.setCategoryFirstId(Long.parseLong(cacheList.get(leftPos).getId()));
            ProfessionalQuoteActivity.start(ServiceClassFragment.this.getActivity(),entity);
        });
        mViewModel.show_loading.observe(this,Integer ->{
            switch (Integer){
                case 1:
                    DialogHelperNew.showProgressDialog(getActivity(), "数据加载中...").setCanceledOnTouchOutside(false);
                    break;
                case 2:
                    DialogHelperNew.dismissProgressDialog();
                    break;
            }
        });

        mViewModel.toast_live.observe(this,string ->{
            MToast.showToast(ServiceClassFragment.this.getActivity(), string);
        });

        mViewModel.data.observe(this,data ->{
            showCategoryView(data);
        });
        setTabLayoutSelentListener();
    }

    @Override
    protected void onLazyLoad() {
        mViewModel.getServiceType();
    }


    private void showCategoryView(List<ParentAreaEntity<List<ParentAreaEntity<List<ParentAreaEntity>>>>> cacheList) {
        if (cacheList != null && cacheList.size() > 0) {
            //过滤没有二级分类的一级分类
            leftAdapter.setDefItem(0);
            leftAdapter.setDatas(cacheList);
            if(cacheList.get(0).getChildren().size()>0) {
                binding.reNullLayout.setVisibility(View.GONE);
                setRightAdapter(0, cacheList.get(0).getChildren());
                binding.rightRecycler.setVisibility(View.VISIBLE);
            }else{
                binding.rightRecycler.setVisibility(View.GONE);
                binding.reNullLayout.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setRightAdapter(int leftPosition, List<ParentAreaEntity<List<ParentAreaEntity>>> rightData) {
        ServiceCategoryRightAdapter rightAdapter = new ServiceCategoryRightAdapter(getActivity(), rightData);
        binding.rightRecycler.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        binding.rightRecycler.setAdapter(rightAdapter);
        rightAdapter.setOnItemClick(new AdapterOnItemClick<ParentAreaEntity<List<ParentAreaEntity>>>() {
            @Override
            public void onItemClick(ParentAreaEntity<List<ParentAreaEntity>> listParentAreaEntity, int position) {
                List<ParentAreaEntity<List<ParentAreaEntity<List<ParentAreaEntity>>>>> cacheList  = leftAdapter.getDatas();
                SecerTitleEntity entity = new SecerTitleEntity();
                entity.setCategoryFirstName(cacheList.get(leftPosition).getName());
                entity.setCategoryFirstId(Long.parseLong(cacheList.get(leftPosition).getId()));
                entity.setCategorySecondName(listParentAreaEntity.getName());
                entity.setCategorySecondId(Long.parseLong(listParentAreaEntity.getId()));
                ProfessionalQuoteActivity.start(ServiceClassFragment.this.getActivity(),entity);
            }
        });
    }


    private void setTabLayoutSelentListener() {
        Gson gson = new Gson();
        channelEntityList = gson.fromJson(MkvUtils.get().getString(MkvUtils.CommomData, CacheMarker.LocalHomePageTitle, ""), new TypeToken<List<ChannelEntity>>() {
        }.getType());
        ChannelEntity shareChannel =new ChannelEntity();
        shareChannel.setName("直播分享");
        channelEntityList.add(shareChannel);
        binding.classificationTitle.clearOnTabSelectedListeners();
        for (int i = 0; i < channelEntityList.size(); i++) {
            binding.classificationTitle.addTab(binding.classificationTitle.newTab().setText(channelEntityList.get(i).getName()).setTag(channelEntityList.get(i).getId()));
        }
        binding.classificationTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //这里就可以根据业务需求处理点击事件了。
                if (tab.getText().toString().contains("分享")) {
                    //知识分享
                    SharePermissionUtils.getPermission(getActivity());
                    return;
                }
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, tab.getTag()));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //这里就可以根据业务需求处理点击事件了。
                if (tab.getText().toString().contains("分享")) {
                    //知识分享
                    SharePermissionUtils.getPermission(getActivity());
                    return;
                }
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, tab.getTag()));
            }
        });
    }

}